import { Space, Popconfirm, Image as AntdImage, Card, Table, message, Row, Col, Divider } from "antd";
import { Button, Card as SemiCard, List, ButtonGroup } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";

import { GetGateways } from "../../_graphql/organizations";
import { UpdateGatewayDependentedDatabases } from "../../_graphql/organizations";

const OrganizationGateways = () => {
    const { windowInnerHeight, graphqlFetchPlatform, BNTApplicationResourceCenterServiceURL, remoteData } = useModel("global");
    const { currentOrganizationUuid } = useModel("organization.info");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        submitLoading: false,
        gateways: [],
        selectedGateway: {},
    });

    const loadGateways = async () => {
        state.loading = true;
        let res = await graphqlFetchPlatform({ query: GetGateways, variables: { uuid: currentOrganizationUuid } });
        state.gateways = res?.a?.nodes || [];
        let selectedGateway = state.gateways.find((item) => item.networkType === state.selectedGateway.networkType);
        !selectedGateway && state.gateways.length > 0 && (selectedGateway = state.gateways[0]);
        state.selectedGateway = selectedGateway || {};
        state.loading = false;
    };

    useEffect(() => {
        currentOrganizationUuid && loadGateways();
    }, [currentOrganizationUuid]);

    const addInitDatabases = async () => {
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceUrl: BNTApplicationResourceCenterServiceURL,
            serviceName: "/resource/referenceDatabase/organization/getAll",
            params: {},
        });
        if (res) {
            let dependentedDatabases = state.selectedGateway?.dependentedDatabases || [];
            let newData = res?.filter(
                (item) => item.isInit === true && dependentedDatabases.findIndex((_item) => _item.databaseName === item.databaseName) === -1
            );
            res = await graphqlFetchPlatform({
                query: UpdateGatewayDependentedDatabases,
                variables: {
                    uuid: state.selectedGateway.uuid,
                    networkType: state.selectedGateway.networkType,
                    dependentedDatabases: dependentedDatabases.concat(newData),
                },
            });
            if (res) {
                message.success("成功更新组织依赖的数据库模型信息");
                loadGateways();
            }
        }
    };

    const openAddDatabaseModal = async () => {
        setModalTitle("添加依赖的数据库");
        setModalWidth(750);
        setModalComponent(<AddDependentedDatabase selectedGateway={state.selectedGateway} reloadData={loadGateways} />);
        setModalVisible(true);
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 60 - 54 - 2;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={6}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>组织网关列表</span>}
                        headerStyle={{ padding: "10px 14px" }}
                        headerExtraContent={
                            <ButtonGroup>
                                <Button icon={<IconRefresh />} onClick={loadGateways} />
                            </ButtonGroup>
                        }
                        shadows="always"
                        bordered={false}
                        size="default"
                        bodyStyle={{ padding: 1, height: cardBodyHeight }}
                    >
                        <List
                            loading={state.loading}
                            dataSource={state.gateways}
                            style={{ height: cardBodyHeight - 60, overflow: "auto" }}
                            renderItem={(item) => (
                                <List.Item
                                    key={item.soUuid}
                                    className={`list-item ${state.selectedGateway?.networkType === item?.networkType ? "list-selected-item" : ""}`}
                                    style={{ border: "2px solid #eee" }}
                                    onClick={() => (state.selectedGateway = item)}
                                >
                                    <ListItem item={item} />
                                </List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={18}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>依赖的数据库模型</span>}
                        headerStyle={{ padding: "10px 14px" }}
                        headerExtraContent={
                            <ButtonGroup>
                                {/* {currentOrganizationUuid && <Button onClick={addInitDatabases}>添加初始的数据库</Button>} */}
                                {currentOrganizationUuid && (
                                    <Button icon={<IconPlusCircle />} onClick={openAddDatabaseModal}>
                                        添加依赖的数据库
                                    </Button>
                                )}
                            </ButtonGroup>
                        }
                        shadows="always"
                        bordered={false}
                        size="default"
                        bodyStyle={{ padding: 0, height: cardBodyHeight }}
                    >
                        <DependentedDatabases selectedGateway={state.selectedGateway} reloadData={loadGateways} />
                    </SemiCard>
                </Col>
            </Row>
        </div>
    );
};

const ListItem = ({ item }) => {
    return (
        <Space direction="vertical" style={{ width: "100%" }}>
            <div style={{ fontWeight: 800 }}>{item?.notes || "-"}</div>
            <div>{item?.url}</div>
            <Space size={20}>
                <div>{item?.networkType}</div>
                <div>{item?.isPublicServiceGateway ? "默认" : "-"}</div>
                <div>{item?.verifyStatus ? "已审核" : "未审核"}</div>
                <div>{item?.usageStatus ? "已启用" : "未启用"}</div>
                <div>{item?.initializationStatus ? "已初始化" : "未初始化"}</div>
            </Space>
        </Space>
    );
};

const DependentedDatabases = ({ selectedGateway, reloadData }) => {
    const { graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        loading: false,
        submitLoading: false,
        data: [],
    });

    const deleteData = async (record) => {
        state.submitLoading = true;
        let data = selectedGateway.dependentedDatabases.filter((item) => item.uuid !== record.uuid);
        let res = await graphqlFetchPlatform({
            query: UpdateGatewayDependentedDatabases,
            variables: {
                uuid: selectedGateway.uuid,
                networkType: selectedGateway.networkType,
                dependentedDatabases: data,
            },
        });
        if (res) {
            reloadData();
        }
        state.submitLoading = false;
    };

    return (
        <Table
            loading={state.loading}
            dataSource={selectedGateway?.dependentedDatabases || []}
            size="small"
            bordered={true}
            pagination={false}
            rowKey="uuid"
            style={{ paddingTop: 1 }}
        >
            <Table.Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
            <Table.Column title="参考数据库名称" dataIndex="databaseName" align="left" />
            <Table.Column title="参考数据库说明" dataIndex="title" align="left" />
            <Table.Column
                title="操作"
                align="center"
                width={120}
                render={(_, r) => (
                    <Space size={0} split={<Divider type="vertical" />}>
                        {r.isInit === false && (
                            <Popconfirm
                                title="确认要移除该依赖的数据库信息吗?"
                                okButtonProps={{
                                    loading: state.submitLoading,
                                }}
                                placement="topRight"
                                onConfirm={() => deleteData(r)}
                            >
                                <a>移除</a>
                            </Popconfirm>
                        )}
                    </Space>
                )}
            />
        </Table>
    );
};

const AddDependentedDatabase = ({ selectedGateway, reloadData }) => {
    const { graphqlFetchPlatform, remoteData, BNTApplicationResourceCenterServiceURL } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        data: [],
    });

    const loadData = async () => {
        state.loading = true;
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceUrl: BNTApplicationResourceCenterServiceURL,
            serviceName: "/resource/referenceDatabase/organization/getAll",
            params: {},
        });
        state.data = res.filter((item) => selectedGateway?.dependentedDatabases.findIndex((_item) => _item.uuid === item.uuid) === -1) || [];
        state.loading = false;
    };

    useEffect(() => {
        loadData();
    }, []);

    const add = async (record) => {
        let dependentedDatabases = [...selectedGateway.dependentedDatabases];
        dependentedDatabases.push(record);
        let res = await graphqlFetchPlatform({
            query: UpdateGatewayDependentedDatabases,
            variables: {
                uuid: selectedGateway.uuid,
                networkType: selectedGateway.networkType,
                dependentedDatabases: dependentedDatabases,
            },
        });
        if (res) {
            message.success("成功更新组织依赖的数据库模型信息");
            await reloadData();
            await loadData();
            onCloseGlobalModal();
        }
    };

    return (
        <Table loading={state.loading} dataSource={state.data} size="small" bordered pagination={false} rowKey="uuid">
            <Table.Column title="参考数据库名称" dataIndex="databaseName" align="left" />
            <Table.Column title="参考数据库说明" dataIndex="title" align="left" />
            <Table.Column title="操作" align="center" render={(_, r) => <a onClick={() => add(r)}>选择</a>} />
        </Table>
    );
};

export default OrganizationGateways;
